package com.imiku.controller;

import com.imiku.config.RedisTemplateTokenStore;
import com.imiku.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 作者 owen E-mail: 624191343@qq.com
 * @version 创建时间：2018年4月5日 下午19:52:21
 */
@RestController
public class UserAuthController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private MenuService menuService;

    @GetMapping("/del/{accessToken}/{refreshToken}")
    public String hello2(@PathVariable String accessToken, @PathVariable String refreshToken) {
        RedisTemplateTokenStore redisTemplateStore = new RedisTemplateTokenStore();
        redisTemplateStore.setRedisTemplate(redisTemplate);
        redisTemplateStore.removeAccessToken(accessToken);
        redisTemplateStore.removeRefreshToken(refreshToken);
        return "delR";
    }

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @RequestMapping(value = {"/users"}, produces = "application/json") // 获取用户信息。/auth/user
    public Map<String, Object> getCurrentUserDetail() {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("user", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        logger.debug("认证详细信息:" + SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        userInfo.put("authorities", SecurityContextHolder.getContext().getAuthentication().getAuthorities());
        userInfo.put("code", 1);
        userInfo.put("menuList", menuService.findByParentId());
        return userInfo;
    }

    @RequestMapping(value = {"/user"}, produces = "application/json") // 获取用户信息。/auth/user
    public Object getCurrentUser() {
        return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

}
